from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .models import Note

# Create your views here.
def check_login(fn):  # fn 相当于我们的视图函数
    def wrap(request,*args,**kwargs):  # 判断当前用户是否登录
        if 'username' not in request.session or 'uid' not in request.session:
            # 检查cookies
            c_username = request.COOKIES.get('username')
            c_uid = request.COOKIES.get('uid')
            if not c_uid and c_username:
                return HttpResponseRedirect('/user/login')
            else:
                # 回写session
                request.session['username'] = c_username
                request.session['uid'] = c_uid
        return fn(request,*args,**kwargs)
    return wrap


@check_login   #校验登录状态 装饰器
def add_note(request):

    if request.method == 'GET':
        return render(request,'note/add_note.html')

    elif request.method == 'POST':
        #处理数据
        uid = request.session['uid']
        title = request.POST['title']
        content = request.POST['content']
        Note.objects.create(title=title, content=content,user_id=uid)
        return HttpResponse("添加笔记成功")